package com.dongdongshop.mq;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.service.FreemarkerService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQMessageListener(topic = "dongdong", consumerGroup = "dk_2107")
public class MessageListener implements RocketMQListener<Long[]>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private FreemarkerService freemarkerService;

    @Override
    public void onMessage(Long[] longs) {
        System.out.println("接收的消息是:"+longs);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                try{
                    for(MessageExt mes : list){
                        String string = new String(mes.getBody());
                        List<Long> longList = JSONObject.parseArray(string, Long.class);
                        for(Long lid : longList){
                            System.out.println(lid);
                            freemarkerService.createPage(lid);
                        }
                    }
                }catch(Exception e){
                    e.printStackTrace();
                    System.out.println("消息发送失败");
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

    }
}
